#include "stdafx.h"
#include "cz_log.h"

cz_log_callback_MsgW cz_g_pfMsgW = NULL;
cz_log_callback_MsgA cz_g_pfMsgA = NULL;
void* cz_g_pUserData = NULL;

/* DebugPrintfX ---------------------------------------------------------------------------------------------*/
bool cz_log_DebugPrintfW(IN wcharc* pwcsFormat, ...)
{
	wchar* buf;
	va_list arg_list;
	va_start(arg_list, pwcsFormat);

	int size;
	size = _vscwprintf(pwcsFormat, arg_list) + 1;
	buf = static_cast<wchar* >(malloc(size * sizeof(wchar)));
	if (buf == NULL) return false;
	vswprintf_s(buf, size, pwcsFormat, arg_list);

	OutputDebugStringW(buf);
	free(buf);

	return true;
}

bool cz_log_DebugPrintfA(IN charc* pstrFormat, ...)
{
	char* buf;
	va_list arg_list;
	va_start(arg_list, pstrFormat);

	int size;
	size = _vscprintf(pstrFormat, arg_list) + 1;
	buf = static_cast<char* >(malloc(size * sizeof(char)));
	if (buf == NULL) return false;
	vsprintf_s(buf, size, pstrFormat, arg_list);

	OutputDebugStringA(buf);
	free(buf);

	return true;
}

/* SetMsgFunction ------------------------------------------------------------------------------------------*/
bool cz_log_SetMsgFunctionW(IN cz_log_callback_MsgW pfMsg, IN void* pUserData)
{
	cz_g_pfMsgW = pfMsg;
	cz_g_pUserData = pUserData;
	return true;
}

bool cz_log_SetMsgFunctionA(IN cz_log_callback_MsgA pfMsg, IN void* pUserData)
{
	cz_g_pfMsgA = pfMsg;
	cz_g_pUserData = pUserData;
	return true;
}

/* MsgX ------------------------------------------------------------------------------------------*/
bool cz_log_MsgW(IN wcharc* pwcsFormat, ...)
{
	wchar* buf;
	va_list arg_list;
	va_start(arg_list, pwcsFormat);

	int size;
	size = _vscwprintf(pwcsFormat, arg_list) + 1;
	buf = static_cast<wchar* >(malloc(size * sizeof(wchar)));
	if (buf == NULL) return false;
	vswprintf_s(buf, size, pwcsFormat, arg_list);

	if (cz_g_pfMsgW != NULL)
	{
		if (!cz_g_pfMsgW(buf, cz_g_pUserData))
		{
			free(buf);
			return false;
		}
	}
	free(buf);
	return true;
}

bool cz_log_MsgA(IN charc* pstrFormat, ...)
{
	char* buf;
	va_list arg_list;
	va_start(arg_list, pstrFormat);

	int size;
	size = _vscprintf(pstrFormat, arg_list) + 1;
	buf = static_cast<char* >(malloc(size * sizeof(char)));
	if (buf == NULL) return false;
	vsprintf_s(buf, size, pstrFormat, arg_list);

	if (cz_g_pfMsgA != NULL)
	{
		if (!cz_g_pfMsgA(buf, cz_g_pUserData))
		{
			free(buf);
			return false;
		}
	}
	free(buf);
	return true;
}